package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.pojo.CommonResult;
import org.example.pojo.Payment;
import org.example.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    //http://localhost:8001/payment/find
    @GetMapping("/customer/find")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for(String service : services){
            log.info("service:"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for(ServiceInstance instance : instances){
            //主机名称
            String host = instance.getHost();
            //端口号
            int port = instance.getPort();
            String instanceId = instance.getInstanceId();
            String serviceId = instance.getServiceId();
            log.info("主机名称host:" + host );
            log.info("端口号port:" + port );
            log.info("serviceId:" + serviceId);
            log.info("instanceId:" + instanceId);
        }
        return this.discoveryClient;
    }

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        int result =  paymentService.create(payment);
        if(result > 0){
            //新增成功
            return new CommonResult(200,"添加成功",result);
        }else{
            return new CommonResult(500,"添加失败",null);
        }
    }

    /**
     * 根据ID查询订单
     */
    @GetMapping("/payment/{id}")
    public CommonResult<Payment> findPaymentById(@PathVariable("id") Long id){
        Payment payment =  paymentService.findPaymentById(id);
        if(payment !=  null){
            //查询成功
            return new CommonResult(200,"查询成功",payment);
        }else{
            return new CommonResult(500,"查询失败",null);
        }
    }

}
